import { EventDetail } from '@/api';
import { GetUserInfo } from '@/api/user';
import PointTag from '@/components/PointTag';
import useUserExamine from '@/hooks/useUserExamine';
import { SHARE_IMAGE } from '@/utils';
import { Button, Icon } from '@antmjs/vantui';
import { Image, Text, View } from '@tarojs/components';
import Taro, { useRouter, useShareAppMessage } from '@tarojs/taro';
import { useRequest } from 'taro-hooks';
import { TemplateMessage } from 'types/user';
import useCustomerService from '../../components/useCustomerService';
import useConfirm from '../index/components/useConfirm';
import useInvitationCode from './components/useInvitationCode';

export default function Page() {
  const { data: detail, refresh } = useRequest(
    () => EventDetail({ event_id: router.params?.id! }),
    {
      onSuccess: function (data) {
        if (data?.title) Taro.setNavigationBarTitle({ title: data.title });
      },
    }
  );

  const { data: user } = useRequest(GetUserInfo, {
    cacheKey: 'get:user:info',
  });

  useShareAppMessage(() => {
    return {
      title: '我发现了一个有价值的企业服务平台邀请你加入',
      imageUrl: SHARE_IMAGE,
      path: `/pages/login/share?refer_code=${user?.refer_code || ''}`,
    };
  });

  //报名确认
  const { renderNode: renderConfirmNode, open: openConfirm } = useConfirm({
    detail: detail!,
    onSuccess: function () {
      Taro.showToast({
        title: '报名成功',
        icon: 'success',
      });
      refresh();
    },
  });

  const { renderNode: renderServiceNode, open: openService } =
    useCustomerService();

  //查看核销码
  const { renderNode: renderInvitaion, open: openInvitationCode } =
    useInvitationCode({
      detail: detail!,
    });

  const router = useRouter();

  const { isUserExamine } = useUserExamine();

  return (
    <>
      <View className='bg-white min-h-screen overflow-hidden pb-32'>
        {/* head */}
        <View
          className='h-[430px] bg-cover bg-gray-400 relative overflow-hidden'
          style={{
            backgroundImage: `url(${detail?.img})`,
          }}
        ></View>
        <View className='relative ml-3 mr-3 px-6 pb-4 pt-7 shadow-lg rounded-lg mb-5 -mt-[50px] border-2 border-white bg-[rgba(255,255,255,.8)] backdrop-blur-lg'>
          {/* 官方活动 tag */}
          {detail?.official && (
            <View
              className='w-[100px] h-[32px] bg-cover absolute left-0 top-0'
              style={{
                backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-activity-1.png?v=1.0.0)`,
              }}
            />
          )}
          <Text className=' block text-[36px] font-bold text-black'>
            {detail?.title}
          </Text>

          <View className=' flex items-center justify-between mt-2'>
            <PointTag value={detail?.points || 0} />

            <View className=' px-2 py-[5px] leading-none text-[16px] text-white bg-[#b8c5de] rounded-md'>
              <Text className=' font-bold text-xs'>{detail?.beans}</Text> 帮豆
            </View>
          </View>
        </View>

        <View className=' px-5'>
          {detail?.description && (
            <>
              <Text className=' text-lg text-black font-bold block mb-2'>
                活动介绍
              </Text>
              <View
                className=' text-xs leading-5'
                dangerouslySetInnerHTML={{
                  __html: detail?.description,
                }}
              />
            </>
          )}

          {detail?.event_start && (
            <>
              <Text className=' text-lg text-black font-bold block mb-2 mt-4'>
                活动时间
              </Text>
              <View className='flex items-center'>
                <Icon name='clock' className=' text-warn mr-1' />
                {detail?.event_start}
              </View>
            </>
          )}

          <Text className=' text-lg text-black font-bold block mb-2 mt-4'>
            活动地点
          </Text>
          <View className='flex items-center'>
            <Icon name='location-o' className=' text-gary4 mr-1' />
            {detail?.location}
          </View>

          {Boolean(detail?.expert_list?.length) && (
            <>
              <Text className=' text-lg text-black font-bold block mb-2 mt-4'>
                专家推荐
              </Text>
              <View className=' flex overflow-auto space-x-2 -mx-6 pl-6'>
                {detail?.expert_list?.map((item) => (
                  <View
                    onClick={() => {
                      Taro.navigateTo({
                        url: `/pages/professional/detail?id=${item.id}`,
                      });
                    }}
                    key={item.id}
                    className=' flex-shrink-0 w-[208px] rounded-lg overflow-hidden'
                  >
                    <Image
                      src={item.headimg}
                      className=' w-[208px] h-[208px] block bg-black'
                      mode='aspectFill'
                    />
                    <View className='bg-[#F6F7FB] p-2'>
                      <Text className=' font-bold text-black text-sm block van-ellipsis'>
                        {item.name}
                      </Text>
                      <Text className=' text-[20px] text-gary1 van-multi-ellipsis--l2 mt-1'>
                        {item.description}
                      </Text>
                    </View>
                  </View>
                ))}
              </View>
            </>
          )}
        </View>

        <View
          className=' fixed px-4 left-0 right-0 bottom-0 bg-white pt-2'
          style={{
            paddingBottom: ' env(safe-area-inset-bottom)',
            boxShadow: '-10px 0 10px rgba(0,0,0,.1)',
          }}
        >
          {(detail?.partin && (
            <>
              <View className=' block text-xs text-center text-gary3 mb-2'>
                如需取消报名，请联系{' '}
                <Text className='text-primary' onClick={() => openService()}>
                  平台客服
                </Text>
              </View>
              <Button
                type='primary'
                block
                className=' relative'
                onClick={() => {
                  openInvitationCode();
                }}
              >
                <View
                  className='w-[200px] h-[52px] bg-cover absolute right-0 text-xs text-black flex items-center justify-center -top-[20px]'
                  style={{
                    backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-yellow.svg)`,
                  }}
                >
                  点击查看核销码
                </View>
                报名成功
              </Button>
            </>
          )) || (
            <>
              {((user?.beans || 0) < (detail?.beans || 0) && (
                <View className=' block text-xs text-center text-gary3 mb-2'>
                  帮豆不足，（帮豆余额 {user?.beans}）
                  <Text
                    className=' text-primary font-bold'
                    onClick={async () => {
                      await isUserExamine();
                      Taro.navigateTo({ url: `/pages/my/bangdou/index` });
                    }}
                  >
                    去充值
                  </Text>
                </View>
              )) || (
                <Text className=' block text-xs text-center text-gary3 mb-2'>
                  报名参加活动，现场签到后可获得{detail?.points}积分
                </Text>
              )}

              <Button
                disabled={(user?.beans || 0) < (detail?.beans || 0)}
                type='primary'
                block
                onClick={async () => {
                  if (!user?.id)
                    return Taro.redirectTo({ url: '/pages/login/index' });

                  //@ts-ignore
                  await Taro.requestSubscribeMessage({
                    tmplIds: [
                      TemplateMessage.活动开始提醒,
                      TemplateMessage.预约结果通知,
                      TemplateMessage.积分变动提醒,
                    ],
                    success: function () {},
                    fail: function (e) {},
                  });
                  openConfirm();
                }}
              >
                报名参加
              </Button>
            </>
          )}
        </View>
      </View>

      {renderConfirmNode()}
      {renderServiceNode()}
      {renderInvitaion()}
    </>
  );
}
